package com.rabbit.eap.framework.component;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.rabbit.eap.common.lang.StringUtils;
import com.rabbit.eap.framework.shiro.util.JwtUtil;
import com.rabbit.eap.framework.utils.HttpKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @projectName eap
 * @packageName com.rabbit.eap.framework.component
 * @className MyMetaObjectHandler
 * @author： rabbit
 * @version： 1.0
 * @since： 2020/5/5 22:20
 * <p>Description: MyMetaObjectHandler
 * myatisplus 自动填充
 * </p>

 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    private static String CREATE_TIME="createTime";
    private static String UPDATE_TIME="updateTime";
    private static String CREATE_BY="createBy";
    private static String UPDATE_BY="updateBy";
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        //避免使用metaObject.setValue()
        if (null == this.getFieldValByName(CREATE_TIME,metaObject)) {
            this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        }
        if (null == this.getFieldValByName(UPDATE_TIME,metaObject)) {
            this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
        }
        String userName = getUserName();
        if (StringUtils.isNotBlank(userName)) {
            if (null == this.getFieldValByName(CREATE_BY,metaObject)){
                this.setFieldValByName(CREATE_BY, userName, metaObject);
            }
            if (null == this.getFieldValByName(UPDATE_BY,metaObject)){
                this.setFieldValByName(UPDATE_BY, userName, metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
        String userName = getUserName();
        if (StringUtils.isNotBlank(userName)) {
            if (null == this.getFieldValByName(UPDATE_BY,metaObject)){
                this.setFieldValByName(UPDATE_BY, userName, metaObject);
            }
        }
    }

    @Nullable
    private String getUserName(){
        HttpServletRequest request = HttpKit.getRequest();
        if (request == null) {
            return null;
        }
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(token)) {
            String userName = JwtUtil.getUsername(token);
            return userName;
        }

        return null;
    }
    
}
